package com.dries.portal.admin.security;

import com.dries.portal.admin.bo.AdminUserDetails;
import com.dries.portal.admin.entity.UmsResource;
import com.dries.portal.admin.service.IUmsAdminService;
import com.dries.portal.admin.service.IUmsResourceService;
import com.dries.security.core.component.CustomSecurityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/2 18:21
 */
@Slf4j
@Component
@Transactional
public class AdminUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Resource
    private IUmsAdminService adminService;
    @Resource
    private IUmsResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("表单登录用户名：" + username);
        return buildUser(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("社交登录用户ID：" + userId);
        return buildUser(userId);
    }

    private SocialUserDetails buildUser(String userId) {
        // 根据用户名查找用户信息
        AdminUserDetails admin = adminService.loadUserByUsername(userId);
        return admin;
    }

    @Bean
    public CustomSecurityService customSecurityService() {
        return new CustomSecurityService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {

                Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();;
                List<UmsResource> resourceList = resourceService.listAll();
                for (UmsResource resource : resourceList) {
                    map.put(resource.getUrl(),
                            new SecurityConfig(resource.getId() + ":" + resource.getName()));
                }
                return map;
            }
        };
    }

}
